<template>
    <div>
      <el-tabs v-model="activeName" id="userTaskProps">
        <el-tab-pane label="用户任务" name="first">
          <el-form>
            <el-form-item label="编号" required>
                <el-input v-model= "id" readonly></el-input>
            </el-form-item>
            <el-form-item label="名称" required>
                <el-input v-model= "name"></el-input>
            </el-form-item>
            <el-form-item label="派遣SQL" icon="el-icon-warning-outline" required>
              <el-tooltip class="item" effect="light" placement="right">
                <template slot="content">
                  select ${userId} as 'userId'<br/>
                  sql中的变量支持：<br/>
                  ${loginUserId}:当前登录用户ID<br/>
                  ${loginName}:当前登录用户登录名<br/>
                  ${loginUserDeptId}:当前登录用户部门Id<br/>
                  ${loginUserDeptCode}:当前登录用户部门编号<br/>
                </template>
                <i class="el-icon-warning"></i>
              </el-tooltip>
              <el-input v-model="assigneeSql" type="textarea" :rows="8"/>
            </el-form-item>
            <el-form-item label="表单ID" required>
              <el-input v-model="formKey"/>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="高级" name="second">
          <el-form>
            <el-form-item label="排它分支条件">
              <el-button type="text" @click="forkCondition=forkConditionExample">导入案例</el-button>
              <el-button type="text" @click="forkCondition={}">清空</el-button>
            </el-form-item>
            <vue-json-editor v-model="forkCondition" mode="code" :show-btns="false" :exapndedOnStart="true" style="height: 300px"/>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <!-- 添加弹出框 -->
      <el-dialog title="任务派遣" :visible.sync="dialogVisible4taskAssign" :close-on-click-modal="false" append-to-body width="80%">
        <!--<MyCtcEventRuleAsideO2MWf :ruleNumberString="ruleNumberString" :dialogVisible4taskAssign="dialogVisible4taskAssign"></MyCtcEventRuleAsideO2MWf>-->
        <!--<div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible4taskAssign=false">
            关闭
          </el-button>
        </div>-->
      </el-dialog>
    </div>
</template>
<script>
import {editTreeJsonById} from "@/views/tmpt/tmpt/api/tmpt-list-api";

const forEach = require('lodash/forEach');
import {findObjFromArrayByField,isNeedUpdate} from '../js/util/CommonUtils';
import bpmnHelper from '../js/helper/BpmnHelper';
import {NodeTypeMap,TxTypeMap} from '../../static/js/static';

//import MyCtcEventRuleAsideO2MWf from '../../../../coding/city/ctcEventRule/my-aside-o2m-wf';
import vueJsonEditor from 'vue-json-editor'
import elementHelper from "@/views/flow/act/edit-modeler/js/helper/ElementHelper";

// 用户任务属性组件
export default {
    props:['element','dialogVisible'],
    inject: ['bpmnModeler'],
    components: {vueJsonEditor},
    data(){
        return {
            activeName: 'first',
            modeling: null,
            id: this.element.id || '',
            ruleNumberString: '',
            name: '',
            forkCondition: '',
            formKey:'',
            documentation: '',
            multiinstance_type: '',
            multiinstance_collection: '',
            multiinstance_condition: '',
            multiinstance_cardinality: null,
            multiinstance_variable: null,
            assignee:'',
            candidateUsers:'',
            // 原子节点属性
            positions:[],
            priority:'',
            candidateGroups: '没有受让人',
            // 任务派遣
            dialogVisible4taskAssign: false,
            forkConditionExample:
              {
                "name":"fork",
                "list":
                  [
                    {"name":"完成任务","val":1},
                    {"name":"转城管","val":2}
                  ]
              },
            timer: undefined,
            assigneeSql:'',
        }
    },

    methods:{
      getFieldValueFromXml(fieldName, fromListener) {
        let fieldValue = ''
        if (this.element && this.element.businessObject && this.element.businessObject.extensionElements && this.element.businessObject.extensionElements.values) {
          this.element.businessObject.extensionElements.values.forEach(listener => {
            if (listener.delegateExpression === fromListener) {
              listener.fields.forEach(field => {
                if (field.name === fieldName) {
                  if (!this.isNull(field.string)) {
                    fieldValue = field.string
                  }else{
                    fieldValue = ''
                  }
                }
              })
            }
          })
        }
        return fieldValue
      },
      appendFieldToElement(fieldName, fieldValue, toListener) {
        if (this.element && this.element.businessObject && this.element.businessObject.extensionElements && this.element.businessObject.extensionElements.values) {
          this.element.businessObject.extensionElements.values.forEach(listener=>{
            if (listener.delegateExpression===toListener) {
              let isExist = false;
              //fork存在话，直接用
              listener.get('fields').forEach(field => {
                if (field.name === fieldName) {
                  field.string = fieldValue
                  isExist = true
                }
              })
              //fork不存在，重新插入
              if (!isExist) {
                let field = elementHelper.createElement('activiti:Field', null, this.element, this.bpmnModeler().get('bpmnFactory'));
                field.name = fieldName
                field.string = fieldValue
                listener.get('fields').push(field)
              }

            }
          })
        }
      },
      clearTimer() {
        if(this.timer) {
          clearInterval(this.timer);
        }
        this.timer = undefined
      }
    },
    mounted() {
        const bpmnModeler = this.bpmnModeler();
        this.modeling = bpmnModeler.get('modeling');
        //console.log('user task mounted')
        //this.initRuleNumberString()
    },
    beforeDestroy() {
      this.clearTimer()
    },
    //监视器
    watch:{
        'dialogVisible': {
          // immediate: true,
          handler: function (nval) {
            if (!nval) {
              this.clearTimer()
            }
          },
        },
        name: {
            handler(newVal, oldVal) {
                this.modeling.updateProperties(this.element,{'name': newVal});
            }
        },
        forkCondition: {
            handler(newVal, oldVal) {
              let forkString = ''
              if (this.isNull(newVal) || JSON.stringify(newVal)==='{}') {
                forkString = ''
              } else {
                forkString = JSON.stringify(newVal)
              }
              this.appendFieldToElement('fork', forkString, '${assigneeListener}')
            }
        },
        assigneeSql: {
            handler(newVal, oldVal) {
                this.appendFieldToElement('assigneeSql', newVal, '${assigneeListener}')
            }
        },
        //监视元素变化
        element:{
            deep: true,
            immediate: true,
            handler(newVal,oldVal){
               if(newVal!=undefined && newVal.type == 'bpmn:UserTask') {
                   const bpmnModeler = this.bpmnModeler();
                   const modeling = bpmnModeler.get('modeling');
                   const businessObject = newVal.businessObject;
                   this.name = businessObject.name;
                   this.formKey = businessObject.get('formKey');
                   // 原子
                   const candidateGroupsTemp = businessObject.get('candidateGroups');
                   // 解决后端反显和切换节点反显candidateGroupsTemp类型不一致问题
                   if(candidateGroupsTemp && candidateGroupsTemp.length > 0) {
                      if(Array.isArray(candidateGroupsTemp)) {
                          //切换节点反显
                          this.candidateGroups = businessObject.get('candidateGroups');
                      } else {
                          //后端反显
                          this.candidateGroups = businessObject.get('candidateGroups').split(',');
                      }
                   }
                   this.multiinstance_type = businessObject.get('multiinstance_type') || 'None';
                   this.multiinstance_condition = businessObject.get('multiinstance_condition') || '';
                   this.assignee=businessObject.get('assignee')||'';
                   this.candidateUsers=businessObject.get('candidateUsers')||'';
                   modeling.updateProperties(newVal,{'multiinstance_type':this.multiinstance_type});
                   modeling.updateProperties(newVal,{'multiinstance_condition':this.multiinstance_condition});
                   modeling.updateProperties(newVal,{'assignee':this.assignee});
                   modeling.updateProperties(newVal,{'candidateUsers':this.candidateUsers});

                   //
                   this.assigneeSql = this.getFieldValueFromXml('assigneeSql','${assigneeListener}')
                   //
                   const forkCondition = this.getFieldValueFromXml('fork','${assigneeListener}')
                   if (!this.isNull(forkCondition)) {
                      this.forkCondition = JSON.parse(forkCondition);
                   }

               }
            }
        },
        formKey:{
            handler(newVal,oldVal){
                this.modeling.updateProperties(this.element,{'formKey':newVal});
            }
        },
        multiinstance_type: {
            handler(newVal, oldVal) {
                this.modeling.updateProperties(this.element,{'multiinstance_type':newVal});
            }
        },
        multiinstance_collection: {
            handler(newVal, oldVal) {
                this.modeling.updateProperties(this.element,{'multiinstance_collection':newVal});
            }
        },
        multiinstance_condition: {
            handler(newVal, oldVal) {
                this.modeling.updateProperties(this.element,{'multiinstance_condition':newVal});
            }
        },
        priority: {
            handler(newVal, oldVal) {
                this.modeling.updateProperties(this.element,{'priority':newVal});
            }
        },
        candidateGroups: {
            handler(newVal,oldVal){
                this.modeling.updateProperties(this.element,{'candidateGroups':newVal});
            }
        },
        assignee:{
             handler(newVal,oldVal){
                this.modeling.updateProperties(this.element,{'assignee':newVal});
            }
        },
        candidateUsers:{
             handler(newVal,oldVal){
                this.modeling.updateProperties(this.element,{'candidateUsers':newVal});
            }
        }

    }

}
</script>
<style>
  /* jsoneditor右上角默认有一个链接,加css去掉了 */
  #userTaskProps .jsoneditor-poweredBy{
    display: none;
  }
  #userTaskProps .jsoneditor-vue{
    height: 100%;
  }

  #userTaskProps .jsoneditor-menu {
    background-color: #dedede !important;
    border-bottom: 1px solid #dfdfdf !important;
  }
  #userTaskProps .jsoneditor {
    border: 1px solid #dfdfdf !important;
  }
  #userTaskProps .jsoneditor-menu > button, div.jsoneditor-menu > div.jsoneditor-modes > button {
    color: #333333;
  }

</style>
